<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="名称" prop="productName">
        <el-input
          v-model="queryParams.productName"
          placeholder="请输入商品名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="编码" prop="productCode">
        <el-input
          v-model="queryParams.productCode"
          placeholder="请输入商品编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="分类" prop="categoryId">
        <el-input
          v-model="queryParams.categoryId"
          placeholder="请输入分类ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="上架" prop="publishStatus">
        <el-select v-model="queryParams.publishStatus" placeholder="请选择上架状态" clearable>
          <el-option
            v-for="dict in dict.type.ec_is_up_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in dict.type.sys_common_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['fun:product:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['fun:product:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['fun:product:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['fun:product:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['fun:product:import']"
        >导入</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="productList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="SKU管理" align="center" width="130">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="primary"
            plain
            icon="el-icon-s-grid"
            @click="handleManageSku(scope.row)"
            title="管理SKU"
          >管理SKU</el-button>
        </template>
      </el-table-column>
      <el-table-column label="商品ID" align="center" prop="productId" width="120" />
      <el-table-column label="商品名称" align="center" prop="productName" width="150" show-overflow-tooltip>
        <template slot-scope="scope">
          <el-link type="primary" @click="handleUpdate(scope.row)" :underline="false">
            {{ scope.row.productName }}
          </el-link>
        </template>
      </el-table-column>
      <el-table-column label="商品编码" align="center" prop="productCode" width="150" />
      <el-table-column label="创建组织" align="center" width="120">
        <template slot-scope="scope">
          <span>{{ getDeptName(scope.row.orgId) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="商品类型" align="center" prop="productType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.ec_good_type" :value="scope.row.productType"/>
        </template>
      </el-table-column>
      <el-table-column label="主图片" align="center" prop="mainImage" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.mainImage" :width="50" :height="50"/>
        </template>
      </el-table-column>

      <el-table-column label="商品展示价格" align="center" prop="price" width="120">
        <template slot-scope="scope">
          <span>¥{{ scope.row.price }}</span>
        </template>
      </el-table-column>
      <!-- 其他价格和库存相关字段已隐藏，在SKU中配置 -->
      <!-- <el-table-column label="原价" align="center" prop="originalPrice" /> -->
      <!-- <el-table-column label="成本价" align="center" prop="costPrice" /> -->
      <!-- <el-table-column label="库存数量" align="center" prop="stock" /> -->
      <!-- <el-table-column label="库存预警值" align="center" prop="lowStock" /> -->
      <!-- <el-table-column label="重量" align="center" prop="weight" /> -->
      <!-- <el-table-column label="体积" align="center" prop="volume" /> -->
      <el-table-column label="单位" align="center" prop="unit" />
      <el-table-column label="关键词" align="center" prop="keywords" width="150" show-overflow-tooltip />
      <!-- <el-table-column label="商品描述" align="center" prop="description" width="200" show-overflow-tooltip /> -->
      <el-table-column label="销量" align="center" prop="saleCount" />
      <el-table-column label="浏览量" align="center" prop="viewCount" />
      <el-table-column label="评论数" align="center" prop="commentCount" />
      <el-table-column label="是否新品" align="center" prop="isNew">
        <template slot-scope="scope">
          <el-tag :type="scope.row.isNew === '1' ? 'success' : 'warning'" size="mini">
            {{ scope.row.isNew === '1' ? '是' : '否' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="是否热销" align="center" prop="isHot">
        <template slot-scope="scope">
          <el-tag :type="scope.row.isHot === '1' ? 'success' : 'warning'" size="mini">
            {{ scope.row.isHot === '1' ? '是' : '否' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="是否推荐" align="center" prop="isRecommend">
        <template slot-scope="scope">
          <el-tag :type="scope.row.isRecommend === '1' ? 'success' : 'warning'" size="mini">
            {{ scope.row.isRecommend === '1' ? '是' : '否' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="上架状态" align="center" prop="publishStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.ec_is_up_status" :value="scope.row.publishStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="审核状态" align="center" prop="verifyStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.ec_audit_status" :value="scope.row.verifyStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="排序" align="center" prop="sortOrder" />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_common_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" width="150" show-overflow-tooltip />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['fun:product:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['fun:product:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改商品对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="商品名称" prop="productName">
          <el-input v-model="form.productName" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="商品编码" prop="productCode">
          <el-input v-model="form.productCode" placeholder="请输入商品编码" />
        </el-form-item>
        <el-form-item label="分类ID" prop="categoryId">
          <el-input v-model="form.categoryId" placeholder="请输入分类ID" />
        </el-form-item>
        <el-form-item label="品牌ID" prop="brandId">
          <el-input v-model="form.brandId" placeholder="请输入品牌ID" />
        </el-form-item>
        <el-form-item label="商品类型" prop="productType">
          <el-select v-model="form.productType" placeholder="请选择商品类型">
            <el-option
              v-for="dict in dict.type.ec_good_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="主图片" prop="mainImage">
          <image-upload v-model="form.mainImage"/>
        </el-form-item>
        <el-form-item label="商品详情" prop="detail">
          <el-input v-model="form.detail" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input v-model="form.price" placeholder="请输入价格" />
        </el-form-item>
        <el-form-item label="原价" prop="originalPrice">
          <el-input v-model="form.originalPrice" placeholder="请输入原价" />
        </el-form-item>
        <el-form-item label="成本价" prop="costPrice">
          <el-input v-model="form.costPrice" placeholder="请输入成本价" />
        </el-form-item>
        <el-form-item label="库存数量" prop="stock">
          <el-input v-model="form.stock" placeholder="请输入库存数量" />
        </el-form-item>
        <!-- <el-form-item label="库存预警值" prop="lowStock">
          <el-input v-model="form.lowStock" placeholder="请输入库存预警值" />
        </el-form-item> -->
        <!-- <el-form-item label="重量" prop="weight">
          <el-input v-model="form.weight" placeholder="请输入重量" />
        </el-form-item>
        <el-form-item label="体积" prop="volume">
          <el-input v-model="form.volume" placeholder="请输入体积" />
        </el-form-item> -->
        <el-form-item label="单位" prop="unit">
          <el-input v-model="form.unit" placeholder="请输入单位" />
        </el-form-item>
        <el-form-item label="关键词" prop="keywords">
          <el-input v-model="form.keywords" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="商品描述" prop="description">
          <editor v-model="form.description" :min-height="192"/>
        </el-form-item>
        <el-form-item label="销量" prop="saleCount">
          <el-input v-model="form.saleCount" placeholder="请输入销量" />
        </el-form-item>
        <el-form-item label="浏览量" prop="viewCount">
          <el-input v-model="form.viewCount" placeholder="请输入浏览量" />
        </el-form-item>
        <el-form-item label="评论数" prop="commentCount">
          <el-input v-model="form.commentCount" placeholder="请输入评论数" />
        </el-form-item>
        <el-form-item label="是否新品" prop="isNew">
          <el-radio-group v-model="form.isNew">
            <el-radio label="1">是</el-radio>
            <el-radio label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否热销" prop="isHot">
          <el-radio-group v-model="form.isHot">
            <el-radio label="1">是</el-radio>
            <el-radio label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否推荐" prop="isRecommend">
          <el-radio-group v-model="form.isRecommend">
            <el-radio label="1">是</el-radio>
            <el-radio label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="上架状态" prop="publishStatus">
          <el-radio-group v-model="form.publishStatus">
            <el-radio
              v-for="dict in dict.type.ec_is_up_status"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审核状态" prop="verifyStatus">
          <el-radio-group v-model="form.verifyStatus">
            <el-radio
              v-for="dict in dict.type.ec_audit_status"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="排序" prop="sortOrder">
          <el-input v-model="form.sortOrder" placeholder="请输入排序" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in dict.type.sys_common_status"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="删除标志" prop="delFlag">
          <el-radio-group v-model="form.delFlag">
            <el-radio
              v-for="dict in dict.type.ec_delete_status"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 商品导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip">
            <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的商品数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listProduct, getProduct, delProduct, addProduct, updateProduct } from "@/api/fun/product"
import { getDept } from "@/api/system/dept"
import CacheManager from '@/utils/cacheManager'
import Editor from "@/components/Editor"
import ImagePreview from "@/components/ImagePreview"
import ImageUpload from "@/components/ImageUpload"

export default {
  name: "Product",
  dicts: ['sys_common_status', 'ec_is_up_status', 'ec_audit_status', 'ec_good_type', 'ec_delete_status'],
  components: { Editor, ImagePreview, ImageUpload },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商品表格数据
      productList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        productName: null,
        productCode: null,
        categoryId: null,
        brandId: null,
        productType: null,
        mainImage: null,

        detail: null,
        price: null,
        originalPrice: null,
        costPrice: null,
        stock: null,
        lowStock: null,
        weight: null,
        volume: null,
        unit: null,
        keywords: null,
        description: null,
        saleCount: null,
        viewCount: null,
        commentCount: null,
        isNew: null,
        isHot: null,
        isRecommend: null,
        publishStatus: null,
        verifyStatus: null,
        sortOrder: null,
        status: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        productName: [
          { required: true, message: "商品名称不能为空", trigger: "blur" }
        ],
        categoryId: [
          { required: true, message: "分类ID不能为空", trigger: "blur" }
        ],
        price: [
          { required: true, message: "价格不能为空", trigger: "blur" }
        ],
      },
      // 导入参数
      upload: {
        // 是否显示弹出层（导入）
        open: false,
        // 弹出层标题（导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的商品数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + this.$store.getters.token },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/fun/product/importData"
      }
    }
  },
  created() {
    this.getList()
  },
  mounted() {
    // 监听表单提交事件
    this.$eventBus.$on('refreshProductList', () => {
      this.getList()
    })
  },
  beforeDestroy() {
    // 移除事件监听器
    this.$eventBus.$off('refreshProductList')
  },
  methods: {    /** 根据部门ID获取部门名称 */
    getDeptName(deptId) {
      return CacheManager.getDeptName(deptId, getDept)
    },
    /** 查询商品列表 */
    getList() {
      this.loading = true
      listProduct(this.queryParams).then(response => {
        this.productList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        productId: null,
        productName: null,
        productCode: null,
        categoryId: null,
        brandId: null,
        productType: null,
        mainImage: null,

        detail: null,
        price: null,
        originalPrice: null,
        costPrice: null,
        stock: null,
        lowStock: 0,
        weight: null,
        volume: null,
        unit: null,
        keywords: null,
        description: null,
        saleCount: null,
        viewCount: null,
        commentCount: null,
        isNew: null,
        isHot: null,
        isRecommend: null,
        publishStatus: null,
        verifyStatus: null,
        sortOrder: null,
        status: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.productId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      const obj = { path: "/fun/product/form", query: { pageType: "add" } };
      this.$tab.openPage("新增商品", obj.path, obj.query);
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      const productId = row.productId || this.ids;
      const obj = { path: "/fun/product/form", query: { pageType: "edit", productId: productId } };
      this.$tab.openPage("修改商品", obj.path, obj.query);
    },
    /** 管理SKU按钮操作 */
    handleManageSku(row) {
      this.$router.push({
        path: '/fun/sku',
        query: {
          productId: row.productId
        }
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.productId != null) {
            updateProduct(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
              // 刷新父页面数据
              this.$tab.refreshPage()
            })
          } else {
            addProduct(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
              // 刷新父页面数据
              this.$tab.refreshPage()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const productIds = row.productId || this.ids
      this.$modal.confirm('是否确认删除商品编号为"' + productIds + '"的数据项？').then(function() {
        return delProduct(productIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('fun/product/export', {
        ...this.queryParams
      }, `product_${new Date().getTime()}.xlsx`)
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "商品导入"
      this.upload.open = true
    },
    /** 下载模板操作 */
    importTemplate() {
      const link = document.createElement('a')
      link.href = process.env.BASE_URL + 'templates/product_import_template.xlsx'
      link.download = `product_template_${new Date().getTime()}.xlsx`
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false
      this.upload.isUploading = false
      this.$refs.upload.clearFiles()
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true })
      this.getList()
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit()
    }
  }
}
</script>
